<template>
  <div class="page-header-wrapper" style="width: 100%; max-width: none">
    <a-modal
      v-model:visible="TimerVisible"
      title="选择类型"
      @ok="TimerHandleOk"
      @cancel="handleCancel"
    >
      <a-radio-group v-model="Timertype">
        <a-radio value="ONE"> 今天不在提醒 </a-radio>
        <a-radio value="ZERO"> 从此不在提醒 </a-radio>
      </a-radio-group>
    </a-modal>
    <!-- 快速发起 -->
    <QuickLaunch ref="quickLaunch" />
    <div class="agent" style="padding: 0px">
      <a-tabs
        default-active-key="1"
        v-model:active-key="agentmenu"
        :tab-bar-style="{ margin: '0px 0px 0px 16px' }"
        @change="teamorpersonal()"
      >
        <a-tab-pane key="1" force-render>
          <template #title>
            <span class="bold-tab" style="font-size: 18px"
              >个人待办({{ data.length }})</span
            >
          </template>
          <a-spin :loading="agentspinning">
            <div class="workplace-split">
              <div class="split-left">
                <TaskList
                  v-model:query="queryParam.name"
                  :items="searchrows"
                  :selectedId="selectagent?.runTaskId"
                  :placeholder="'输入搜索'"
                  :titleFormatter="
                    (it) => cropname(it.serviceItemTitle, it.createName)
                  "
                  :dateFormatter="transferDate"
                  :getId="(it) => it.runTaskId"
                  :getTip="(it) => it.tip"
                  :getTag="(it) => it.tag"
                  :parsedTag="(it) => JSON.parse(it.tag)"
                  :getNodeName="(it) => it.nodeName"
                  :getCreateTime="(it) => it.createTime"
                  @select="examineClick"
                />
              </div>
              <div class="split-right">
                <TaskDetail
                  ref="approVal"
                  :select="selectagent"
                  :approve="Approve"
                  :approveShow="ApproveShow"
                  :innerActiveKey="activeKey"
                  :appVisible="appVisible"
                  :approVal="approVal"
                  :approvalButton="approvalButton"
                  :buttonMap="buttonMap"
                  :fromList="fromList"
                  :participate="participate"
                  :showFlow="false"
                  :wokflowSpinning="wokflowSpinning"
                  :nodekeyMap="nodekeyMap"
                  :styleData="styleData"
                  :dateFormatter="transferDate"
                  :getButtonClass="getButtonClass"
                  @toggle-approve="ApproveShow = !ApproveShow"
                  @change-tab="callbackTab"
                  @submit="handleOk"
                />
              </div>
            </div>
          </a-spin>
        </a-tab-pane>
        <a-tab-pane v-if="false" key="2">
          <template #title>
            <span class="bold-tab" style="font-size: 18px"
              >团队待办({{ teamData.length }})</span
            >
          </template>
          <a-spin :loading="agentspinning">
            <a-row type="flex">
              <a-col :span="7">
                <div class="cardList">
                  <a-input
                    style="margin-bottom: 8px"
                    :allow-clear="true"
                    class="custom-input"
                    v-model="teamqueryParam.name"
                    placeholder="输入搜索"
                  >
                    <template #suffix>
                      <a-tooltip>
                        <template #content>搜索</template>
                        <span
                          v-if="!teamqueryParam"
                          style="color: var(--color-text-3)"
                          >🔍</span
                        >
                      </a-tooltip>
                    </template>
                  </a-input>
                  <div v-if="teamData.length !== 0" class="scroll-container">
                    <div
                      :style="{
                        margin: index == 0 ? '0px 0px 8px 0px' : '8px 0px',
                      }"
                      :class="{
                        active:
                          item?.runExecutionId ===
                          teamSelectagent?.runExecutionId,
                      }"
                      v-for="(item, index) in teansearchrows"
                      :key="index"
                      class="card"
                      @click="
                        item?.runExecutionId !== teamSelectagent?.runExecutionId
                          ? getTeamTaskDetail(item)
                          : false
                      "
                    >
                      <div>
                        <ul style="display: flex">
                          <li>
                            <div
                              style="
                                font-size: 16px;
                                font-weight: bold;
                                color: var(--color-text-1);
                              "
                            >
                              <OverflowText
                                style="font-weight: 500"
                                :text="
                                  cropname(
                                    item.serviceItemTitle,
                                    item.createName
                                  )
                                "
                                :maxWidth="'235px'"
                              />
                            </div>
                          </li>
                          <li>
                            <div>
                              <a-tooltip
                                v-if="item.tip"
                                placement="top"
                                :title="`${item.tip}`"
                              >
                                <div
                                  class="iconRemark"
                                  style="
                                    width: 20px;
                                    height: 20px;
                                    padding: 3px;
                                    display: flex;
                                    margin-top: 1px;
                                  "
                                >
                                  <svg
                                    class="icon"
                                    style="
                                      font-size: 14px;
                                      color: var(--color-text-2);
                                    "
                                    aria-hidden="true"
                                  >
                                    <use xlink:href="#icon-beizhu"></use>
                                  </svg>
                                </div>
                              </a-tooltip>
                            </div>
                          </li>
                        </ul>
                      </div>
                      <div v-if="item.tag">
                        <span
                          style="display: flex; margin: 0px; padding: 3px"
                          v-for="(value, key, tagindex) in JSON.parse(item.tag)"
                          :key="tagindex"
                        >
                          <div
                            style="
                              font-size: 13px;
                              color: var(--color-text-2);
                              font-size: 14px;
                            "
                          >
                            {{ key }}
                          </div>
                          <div
                            style="
                              color: var(--color-text-1);
                              padding-left: 5px;
                              font-size: 14px;
                            "
                          >
                            :{{ value }}
                          </div>
                        </span>
                      </div>
                      <div>
                        <ul style="display: flex; height: 23px">
                          <li>
                            <div class="syletag">
                              <OverflowText
                                style="background: var(--color-warning-1)"
                                color="var(--color-warning-6)"
                                :text="item.nodeName"
                                :maxWidth="'150px'"
                              />
                            </div>
                          </li>
                          <li>
                            <div
                              class="limited-container"
                              style="
                                color: var(--color-text-3);
                                font-size: 12px;
                                line-height: 20px;
                              "
                            >
                              <p v-if="item.nodeName">
                                <span>
                                  {{
                                    JSON.stringify(item.nodeName).length < 9
                                      ? "发起时间"
                                      : ""
                                  }}
                                  {{ transferDate(item.createTime) }}</span
                                >
                              </p>
                              <p v-else>
                                <span
                                  >发起时间:
                                  {{ transferDate(item.createTime) }}</span
                                >
                              </p>
                            </div>
                          </li>
                        </ul>
                      </div>
                    </div>
                  </div>
                  <div
                    v-else
                    style="
                      color: var(--color-text-3);
                      text-align: center;
                      margin-top: 100px;
                    "
                  >
                    暂无数据
                  </div>
                </div>
              </a-col>
              <a-col :span="17" style="border-radius: 0px 0px 8px 0px">
                <div
                  class="agentcontent no-scroll-container"
                  style="height: 100%"
                >
                  <div v-if="teamSelectagent" class="agent">
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                      "
                    >
                      <ul style="justify-content: left">
                        <li
                          style="
                            margin-right: 12px;
                            font-size: 18px;
                            font-weight: 500;
                            color: var(--color-text-1);
                          "
                        >
                          {{ teamSelectagent.serviceItemTitle }}
                        </li>
                        <a-divider
                          style="
                            background: var(--color-border-2);
                            margin-right: 12px;
                            width: 1px;
                            height: 14px;
                            border-radius: 1px;
                            margin-top: 2px;
                          "
                          type="vertical"
                        />
                        <li
                          style="
                            margin-right: 12px;
                            display: flex;
                            align-items: center;
                          "
                        >
                          <img
                            style="width: 20px; height: 20px; margin-right: 4px"
                            src="https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
                          />
                          <div
                            style="
                              font-size: 14px;
                              color: var(--color-text-3);
                              font-weight: 400;
                            "
                          >
                            <OverflowText
                              style="
                                font-size: 14px;
                                line-height: 14px;
                                color: var(--color-text-1);
                                padding-left: 5px;
                              "
                              :text="teamSelectagent.createName"
                              :maxWidth="'100px'"
                            />
                          </div>
                        </li>
                        <li style="margin-right: 24px">
                          <div
                            style="
                              display: flex;
                              align-items: center;
                              font-size: 14px;
                              color: var(--color-text-3);
                              font-weight: 400;
                              line-height: 16px;
                            "
                          >
                            <div>发起于</div>
                            <div style="padding-left: 5px">
                              {{ transferDate(teamSelectagent.createTime) }}
                            </div>
                          </div>
                        </li>
                        <li style="line-height: 16px">
                          <div style="display: flex; align-items: center">
                            <div
                              style="
                                font-size: 14px;
                                color: var(--color-text-3);
                                line-height: 16px;
                                font-weight: 400;
                              "
                            >
                              节点名称:
                            </div>
                            <div
                              style="
                                color: var(--color-text-1);
                                padding-left: 5px;
                                margin-top: 3px;
                              "
                            >
                              {{ teamSelectagent.nodeName }}
                            </div>
                          </div>
                        </li>
                      </ul>
                      <a-tooltip
                        v-if="
                          Approve.log && Approve.log.length > 0 && !ApproveShow
                        "
                        :content="'展开上一节点处理结果'"
                      >
                        <div
                          @click="
                            () => {
                              ApproveShow = !ApproveShow;
                            }
                          "
                          class="expand"
                        >
                          详情
                          <svg
                            class="icon"
                            style="font-size: 12px; line-height: 20px"
                            aria-hidden="true"
                          >
                            <use xlink:href="#icon-a-zhankaishouqi"></use>
                          </svg>
                        </div>
                      </a-tooltip>
                    </div>
                    <div
                      ref="approveDom"
                      v-if="
                        Approve.log && Approve.log.length > 0 && ApproveShow
                      "
                      style="
                        position: relative;
                        background: var(--color-fill-1);
                        border: 1px dashed var(--color-primary-3);
                        border-radius: 6px;
                        padding: 8px 12px;
                        margin-top: 8px;
                      "
                    >
                      <div
                        style="
                          height: 20px;
                          font-weight: 500;
                          font-size: 14px;
                          color: var(--color-text-2);
                          line-height: 20px;
                        "
                      >
                        {{ Approve.nodeName }}
                      </div>
                      <div
                        @click="
                          () => {
                            ApproveShow = !ApproveShow;
                          }
                        "
                        style="
                          cursor: pointer;
                          position: absolute;
                          top: 0px;
                          right: 0px;
                          height: 24px;
                          background: var(--color-fill-2);
                          border-radius: 0px 5px 0px 11px;
                          padding: 4px 10px;
                          color: var(--color-text-2);
                          line-height: 16px;
                          font-size: 12px;
                        "
                      >
                        {{ !ApproveShow ? "详情" : "折叠" }}
                        <svg
                          class="icon"
                          style="
                            transform: rotate(180deg);
                            font-size: 12px;
                            line-height: 20px;
                          "
                          aria-hidden="true"
                        >
                          <use xlink:href="#icon-a-zhankaishouqi"></use>
                        </svg>
                      </div>
                      <div class="scroll-container" style="max-height: 170px">
                        <div
                          style="margin-top: 8px"
                          v-for="(Approveitem, Approveindex) in Approve.log"
                          :key="Approveindex"
                        >
                          <div style="display: flex; margin-bottom: 6px">
                            <div style="margin-right: 4px">
                              <img
                                style="
                                  width: 20px;
                                  height: 20px;
                                  margin-right: 5px;
                                "
                                src="https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
                              />
                            </div>
                            <div
                              style="
                                margin-right: 8px;
                                color: var(--color-text-1);
                                font-size: 14px;
                                line-height: 22px;
                              "
                            >
                              {{ Approveitem.user_name }}
                            </div>
                            <div
                              style="
                                font-size: 12px;
                                line-height: 21px;
                                color: var(--color-text-3);
                              "
                            >
                              {{ Approveitem.complete_date }}
                            </div>
                          </div>
                          <div style="display: flex; margin-left: 30px">
                            <div
                              style="
                                text-align: end;
                                width: 45px;
                                font-size: 14px;
                                color: var(--color-primary-6);
                                line-height: 20px;
                                margin-right: 4px;
                              "
                            >
                              {{ Approveitem.approvalResult }}
                            </div>
                            <div
                              v-if="Approveitem.approvalComments"
                              class="titleUtils"
                              style="
                                color: var(--color-text-3);
                                line-height: 20px;
                                font-size: 14px;
                              "
                            >
                              ({{ Approveitem.approvalComments }})
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div>
                      <div>
                        <a-tabs
                          v-model:active-key="temeactiveKey"
                          default-active-key="1"
                          force-render
                          @change="teamCallbackTab"
                        >
                          <a-tab-pane key="1">
                            <template #title>
                              <span style="font-size: 13px" class="bold-tab"
                                >节点详情</span
                              >
                            </template>
                            <div
                              class="scroll-container"
                              style="
                                padding: 10px 20px;
                                margin-top: 12px;
                                height: 527px;
                              "
                            >
                              <FormRenderer
                                v-if="TeamAgencyShow"
                                :schema="DetailsdataObj"
                                v-model="DetailsModelValue"
                              />
                            </div>
                            <a-divider style="margin: 10px 0px 0px 0px" />
                            <div
                              style="
                                height: 50px;
                                display: flex;
                                align-items: center;
                                margin-bottom: -8px;
                              "
                            >
                              <a-button
                                type="primary"
                                @click="showConfirm(teamSelectagent)"
                              >
                                <svg
                                  class="icon"
                                  style="font-size: 14px; margin-right: 8px"
                                  aria-hidden="true"
                                >
                                  <use :xlink:href="`#icon-tijiao`"></use>
                                </svg>
                                转为个人待办
                              </a-button>
                            </div>
                          </a-tab-pane>
                          <a-tab-pane key="2">
                            <template #title>
                              <span style="font-size: 13px" class="bold-tab"
                                >流转记录</span
                              >
                            </template>
                            <home-timeline
                              v-if="fromList.length > 0"
                              style="height: 580px"
                              ref="timeline"
                              :fromList="fromList"
                              :participate="participate"
                            ></home-timeline>
                          </a-tab-pane>
                          <a-tab-pane key="3">
                            <template #title>
                              <span style="font-size: 13px" class="bold-tab"
                                >流程图</span
                              >
                            </template>
                            <div>
                              <a-spin :loading="wokflowSpinning">
                                <processSvg
                                  v-if="!wokflowSpinning"
                                  ref="fow"
                                  :nodekeyMap="nodekeyMap"
                                  :styleData="styleData"
                                />
                              </a-spin>
                            </div>
                          </a-tab-pane>
                        </a-tabs>
                      </div>
                    </div>
                  </div>
                  <div
                    v-else
                    class="notData"
                    style="padding: 10px; height: 680px; align-items: center"
                  >
                    <!-- <img src="@/assets/kong.png" /> -->
                  </div>
                </div>
              </a-col>
            </a-row>
          </a-spin>
        </a-tab-pane>
        <a-tab-pane key="3">
          <template #title>
            <span class="bold-tab" style="font-size: 18px">我发起的</span>
          </template>
          <div class="agentcontent no-scroll-container">
            <div class="agent">
              <agencyTasks
                ref="agencyTasks"
                :participate="false"
                @teamorpersonal="teamorpersonal"
              ></agencyTasks>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="4">
          <template #title>
            <span class="bold-tab" style="font-size: 18px">我处理的</span>
          </template>
          <div class="agentcontent no-scroll-container">
            <div class="agent">
              <agencyTasks ref="agencyTasks" :participate="true"></agencyTasks>
            </div>
          </div>
        </a-tab-pane>

        <template #extra>
          <div class="titlerefreshButton" @click="teamorpersonal()">
            <div class="refreshText">刷新</div>
          </div>
        </template>
      </a-tabs>
    </div>
    <div>
      <a-modal
        v-model:visible="userGroupvisible"
        width="500px"
        :unmount-on-close="true"
        title="选择用户组"
        :align-center="true"
        :modal-style="{ top: '10px' }"
        ok-text="确认"
        @ok="userGrouphandleOk"
      >
        <a-radio-group v-model="userGroupIds" :options="userGroupList" />
      </a-modal>
    </div>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
import FormRenderer from "@/components/Form/FormRenderer.vue";
import {
  queryMyTaskDetail,
  dataExec,
  queryCompleted,
  queryTableDesc,
  getUpApprove,
  getNodeExecStatus,
  queryTeamTask,
  getTeamTaskDetail,
  claim,
  chooseTaskByGroup,
  claimUserGroupIds,
  queryTimer as apiQueryTimer,
  delTimer as apiDelTimer,
  complete as apiComplete,
  processCheck as apiProcessCheck,
} from "@/api/workflow2";
import {
  queryWorkPage,
  queryMyTask,
  saveUnlimitedValue,
} from "@/api/workplace";
import { JSONPath } from "jsonpath-plus";
import moment from "moment";
import quickLaunch from "@/views/dashboard/workplace/quickLaunch.vue";
import agencyTasks from "@/views/dashboard/workplace/agencyTasks.vue";
import OverflowText from "@/views/dashboard/workplace/OverflowText.vue";
import TaskList from "@/components/Workplace/TaskList.vue";
import TaskDetail from "@/components/Workplace/TaskDetail.vue";
import { repairUiData } from "@/utils/util.js";
import { processDataCondition } from "@/mixins/methodsMixins.js";

import _ from "lodash";

export default {
  components: {
    FormRenderer,
    QuickLaunch: quickLaunch,
    agencyTasks,
    OverflowText,
    TaskList,
    TaskDetail,
  },
  name: "Home",
  data() {
    return {
      UrlParamsRunTaskId: undefined,
      UrlParamsInstanceId: undefined,
      UrlParamsType: undefined,
      finishData: [],
      data: [],
      teamData: [],
      userGroupList: [],
      userGroupIds: [],
      runExecutionId: null,
      personalSearch: "",
      teamSearch: "",
      divHeight: 0, // 用于存储 div 的高度
      modalObj: { mode: "nodeExe" }, // 模式一定要传
      dataObj: {}, // 未审批详情UI
      DetailsmodalObj: { mode: "nodeExe" },
      DetailsdataObj: {},
      DetailsModelValue: {},
      examineObj: {}, // 详情数据
      agentspinning: false,
      spinning: false,
      wokflowSpinning: false,
      selectagent: null,
      teamSelectagent: null,
      participate: false,
      agencyTasksShow: false,
      workflowdata: {},
      styleData: {},
      nodekeyMap: {},
      nodeIdMap: {},
      approValshow: false,
      ApproveShow: false,
      approvalButton: [],
      Approve: [],
      temeactiveKey: "1",
      activeKey: "1",
      agentmenu: "1",
      queryParam: {},
      teamqueryParam: {},
      approvalStatus: {
        同意: "var(--color-primary-6)",
        拒绝: "var(--color-danger-6)",
        驳回: "var(--color-danger-6)",
      },
      ordertype: [
        // {
        //   key: 'executor',
        //   value: '接单已处理',
        //   color: '#007AFF'
        // },
        {
          key: "notExecutor",
          value: "接单未处理",
          color: "red",
        },
        {
          key: "executorMap",
          value: "团队接单处理人",
          color: "var(--color-fill-3)",
        },
        {
          key: "untreated",
          value: "团队接单未处理人",
          color: "red",
        },
        {
          key: "notAccepted",
          value: "未接单团队",
          color: "var(--color-fill-3)",
        },
      ],
      buttonMap: {
        同意: { icon: "icon-duihao", type: "primary", ghost: true },
        拒绝: { icon: "icon-cuowu", type: "danger", ghost: true },
        驳回: { icon: "icon-chehui", type: "", ghost: false },
        结束: { icon: "icon-guanji", type: "", ghost: false },
      },
      workflowView: {
        ref: "workflowView",
        form: {},
        modalObj: { mode: "nodeExe" },
        dataObj: {},
        key: nanoid(),
      },
      nodeView: {
        ref: "nodeView",
        form: {},
        modalObj: { mode: "nodeExe" },
        dataObj: {},
        key: nanoid(),
      },
      approVal: {
        ref: "approVal",
        form: {},
        modalObj: { mode: "nodeExe" },
        dataObj: {},
        curPlugBtn: {},
        key: nanoid(),
      },
      agencyType: "personal",
      winTitle: "",
      instanceId: "", // 当前进入审批的instanceId
      buttonText: "提交",
      isNone: true,
      modelId: "",
      version: "",
      fromList: [],
      queryTimerList: [],
      visible: false,
      userGroupvisible: false,
      TeamAgencyDetails: false,
      TimerVisible: false,
      TeamAgencyShow: true,
      TimerId: false,
      Timertype: "ONE",
      showComponent: true,
      columns: [
        {
          title: "服务项ID",
          dataIndex: "serviceItemId",
          scopedSlots: { customRender: "serviceItemId" },
        },
        {
          title: "服务项名称",
          dataIndex: "serviceItemTitle",
        },
        {
          title: "执行状态",
          dataIndex: "processStatus",
          scopedSlots: { customRender: "processStatus" },
        },
        {
          title: "标签",
          dataIndex: "tagValue",
          scopedSlots: { customRender: "tagValue" },
          width: "200px",
        },
        {
          title: "开始时间",
          dataIndex: "createTime",
          customRender: (text, record) => {
            return text
              ? moment(parseInt(text)).format("YYYY-MM-DD HH:mm:ss")
              : "";
          },
        },
        {
          title: "结束时间",
          dataIndex: "endTime",
          customRender: (text, record) => {
            return text
              ? moment(parseInt(text)).format("YYYY-MM-DD HH:mm:ss")
              : "";
          },
        },
        {
          title: "操作",
          dataIndex: "action",
          // width: '360px',
          scopedSlots: { customRender: "action" },
        },
      ],
      loadData: (parameter) => {
        const { pageNo, pageSize } = parameter || {};
        return queryWorkPage({
          serviceItemTitle: this.queryParam.name,
          processStatus: this.queryParam.Status,
          instanceId:
            this.UrlParamsInstanceId && this.UrlParamsType === "initiate"
              ? this.UrlParamsInstanceId
              : "",
          pageNo: pageNo,
          pageSize,
        })
          .then((res) => {
            return {
              resultList: res.data.rows,
              total: res.data.page.totalRow,
              current: res.data.page.pageNo,
            };
          })
          .catch(() => {
            return { resultList: [], total: 0, current: 0 };
          });
      },
      searchrows: [],
      teansearchrows: [],
      appVisible: false,
      isOverflow: false,
      resizeObserver: null,
    };
  },
  created() {
    const urlParams = new URLSearchParams(window.location.search);
    this.UrlParamsRunTaskId = urlParams.get("runExecutionId");
    this.UrlParamsInstanceId = urlParams.get("instanceId");
    this.UrlParamsType = urlParams.get("type");
    if (this.UrlParamsType === "time") {
      // 团队待办切换
      this.agentmenu = "2";
    } else if (this.UrlParamsType === "initiate") {
      // 切换到我发起的
      this.loadData();
      this.agentmenu = "3";
      this.participate = false;
      this.agencyTasksShow = true;
    }
    this.initList();
    this.queryTimer();
  },
  mounted() {},
  destroyed() {},
  methods: {
    isObjectEmpty(item) {
      return !_.isEmpty(item); // 使用 Lodash 的 isEmpty 方法
    },
    approvalsIndex(item) {
      // 算几个已处理，狗听了摇头
      let index = 0;
      if (JSON.parse(item[item.length - 1].log)[0]?.result) {
        for (const i of JSON.parse(
          JSON.parse(item[item.length - 1].log)[0]?.result
        )) {
          if (i.approvalResult) {
            index++;
          }
        }
      }
      return index;
    },
    // scrollToBottom () {
    //   const container = this.$refs.scrollContainer
    //   container.scrollTop = container.scrollHeight
    // },
    isJsonString(str) {
      try {
        JSON.parse(str);
        return true;
      } catch (e) {
        return false;
      }
    },
    checkAllOverflow() {
      const contentDivs = this.$refs.ordertype;
      if (contentDivs) {
        contentDivs.forEach((div, index) => {
          // 判断每个 div 内容是否溢出
          if (div.scrollHeight > div.clientHeight) {
            this.showExtraDivs[index] = true;
          } else {
            this.showExtraDivs[index] = false;
          }
        });
      }
    },
    getButtonClass(type) {
      if (type === "primary") {
        return "btn-primary-hover";
      }
      if (type === "danger") {
        return "btn-dashed-hover";
      }
      // 你可以根据更多的类型来添加其他样式
      return "btn-hover";
    },
    cropname(serviceItemTitle, createName) {
      // const strval = `${serviceItemTitle}“${createName}”`
      const strval = `${createName}发起的“${serviceItemTitle}”`;
      return strval;
    },
    async onSearch() {
      // 搜索代办'
      const regex = new RegExp(this.personalSearch, "i"); // "i" 表示忽略大小写
      this.searchrows = this.data.filter(
        (item) => item.serviceItemTitle && regex.test(item.serviceItemTitle)
      );
    },
    async teamonSearch() {
      // 搜索团队代办
      const regex = new RegExp(this.teamSearch, "i"); // "i" 表示忽略大小写
      this.teansearchrows = this.teamData.filter(
        (item) => item.serviceItemTitle && regex.test(item.serviceItemTitle)
      );
    },
    async queryTimer() {
      // 查询当月的
      try {
        const result = await apiQueryTimer();
        const list = Array.isArray(result?.data)
          ? result.data
          : Array.isArray(result?.data?.rows)
            ? result.data.rows
            : [];
        this.queryTimerList = list;
      } catch (e) {
        console.error("queryTimer error", e);
        this.queryTimerList = [];
      }
    },
    async Timerclose(id) {
      // 删除定时任务
      this.TimerId = id;
      this.TimerVisible = true;
    },
    async TimerHandleOk() {
      // 弹窗选类型
      apiDelTimer(this.TimerId, this.Timertype);
      this.TimerVisible = false;
      this.queryTimer();
    },
    async handleCancel() {
      // 取消弹窗
      this.queryTimer();
    },
    async getTeamTaskDetail(item) {
      // nodeID查代办
      this.agentspinning = true;
      try {
        this.ApproveShow = false;
        this.TeamAgencyShow = false;
        this.temeactiveKey = "1";
        this.activeKey = "1";
        this.fromList = [];
        this.teamSelectagent = item;
        const { runExecutionId, version, nodeKey, modelId, instanceId } = item;
        this.runExecutionId = runExecutionId;
        const res = await getTeamTaskDetail({
          nodeKey: nodeKey,
          version: version,
          modelId: modelId,
          instanceId: instanceId,
        });
        this.DetailsdataObj = repairUiData(
          res.data.viewUi,
          res.data.viewDataMappingDTOList
        ); // 这里用查询
        this.TeamAgencyShow = true;
        const result = await queryCompleted({
          instanceId: instanceId,
          modelId: modelId,
          version: version,
          record: true,
          nodeId: res.data.nodeId,
        });
        this.isNone = result.data.showView;
        this.fromList = this.formUiMap(
          result.data.processCompletedNodeResDTOMap
        );
        const param = result.data.param;
        if (param.viewParam !== undefined) {
          const viewParam = JSON.parse(param.viewParam);
          this.DetailsModelValue = viewParam || {};
        } else {
          this.DetailsModelValue = param || {};
        }
        const Approve = await getUpApprove({
          instanceId: instanceId,
          nodeId: res.data.nodeId,
        });
        this.Approve = Approve.data;
      } catch (error) {
        console.error(error);
      }
      this.agentspinning = false;
    },
    async showConfirm(item) {
      if (item.groupType === "user") {
        await claim({
          runExecutionId: this.runExecutionId,
        });
      } else {
        const data = {
          runExecutionId: this.runExecutionId,
        };
        const res = await chooseTaskByGroup(data);
        if (res.data && Object.keys(res.data).length > 0) {
          this.userGroupvisible = true;
          this.userGroupList = Object.entries(res.data).map(([key, value]) => ({
            // label: key,
            // value: value
            label: value,
            value: key,
          }));
        } else {
          const data = {
            departmentIds: [],
            executionId: this.runExecutionId,
            userGroupIds: [],
            userId: "",
          };
          await claimUserGroupIds(data);
        }
      }
      this.initList();
    },
    async userGrouphandleOk() {
      // 确认选择用户组
      const data = {
        departmentIds: [],
        executionId: this.runExecutionId,
        userGroupIds: [this.userGroupIds],
        userId: "",
      };
      await claimUserGroupIds(data);
      this.userGroupvisible = false;
      this.initList();
    },
    async examineClick(val) {
      // 点击审批跳转
      this.agentspinning = true;
      try {
        this.appVisible = false;
        this.ApproveShow = false;
        this.approValshow = false;
        this.approVal.dataObj = {};
        this.approVal.curPlugBtn = {};
        this.approvalButton = [];
        this.fromList = [];
        this.personalSearch = "";
        this.temeactiveKey = "1";
        this.activeKey = "1";
        this.selectagent = val;
        this.workflowView.key = nanoid();
        this.nodeView.key = nanoid();
        this.winTitle = val.nodeName;
        const result = await queryMyTaskDetail({
          runTaskId: val.runTaskId,
        });
        if (!result || !result.data) {
          console.error("queryMyTaskDetail 返回空", result);
          this.agentspinning = false;
          return;
        }
        this.approVal.dataObj = repairUiData(
          result.data.viewUi,
          result.data.viewDataMappingDTOList
        ); // 这里用查询
        this.appVisible = true;
        const dataCondition = JSONPath(
          `$.pageData[?(@.formData.dataIndex == "approvalResult")].formData.dataCondition`,
          this.approVal.dataObj
        );
        const queryId = JSONPath(
          `$.pageData[?(@.formData.dataIndex == "approvalResult")].formData.dataSourceId`,
          this.approVal.dataObj
        )[0];
        if (dataCondition.length > 0) {
          const requestData = {
            dataId: queryId,
            valueMap: processDataCondition(dataCondition[0]),
          };
          if (queryId) {
            const dataExecData = await dataExec(requestData);
            this.approvalButton = dataExecData?.data?.resultPage?.rows || [];
          }
        }
        this.examineObj = result.data;
        this.instanceId = result.data.instanceId;
        this.modelId = result.data.modelId;
        this.version = result.data.version;
        const TaskNodeId = result.data.nodeId;
        const res = await queryCompleted({
          instanceId: result.data.instanceId,
          modelId: result.data.modelId,
          version: result.data.version,
          record: true,
          nodeId: TaskNodeId,
        });
        this.isNone = res?.data?.showView ?? true;
        this.fromList = this.formUiMap(
          res?.data?.processCompletedNodeResDTOMap || {}
        );
        const param = res?.data?.param || {};
        const nodeUi = result.data.nodeUi;
        if (nodeUi) {
          const curPlugBtn = JSON.parse(nodeUi).curPlugBtn;
          if (curPlugBtn) {
            const buttonId = JSON.parse(curPlugBtn).buttonId;
            const eventId = JSON.parse(curPlugBtn).eventId;
            const result = await queryTableDesc(buttonId);
            this.dataSourceUiMapDTOList =
              result?.data?.dataSourceUiMapDTOList || []; // 审批的map
            const tableButtonReqDTOList =
              result?.data?.tableButtonReqDTOList || [];
            const param = JSONPath(
              `$[?(@.tableButtonAddDTO.eventId=="${eventId}")]`,
              tableButtonReqDTOList
            )[0];
            const cpparam = JSON.parse(JSON.stringify(param));
            this.approVal.curPlugBtn = cpparam;
          }
        }
        // this.appVisible = true
        if (param && param.viewParam !== undefined) {
          const viewParam = JSON.parse(param.viewParam);
          await this.$refs.approVal.uploadInitlist(viewParam);
          this.approVal.form = viewParam;
        } else if (param) {
          await this.$refs.approVal.uploadInitlist(param);
          this.approVal.form = param;
        }
        const Approve = await getUpApprove({
          instanceId: result.data.instanceId,
          nodeId: TaskNodeId,
        });
        this.Approve = Approve?.data || [];
      } catch (error) {
        console.error(error);
      }
      this.agentspinning = false;
    },
    async flowchart(data) {
      // 流程图
      this.wokflowSpinning = true;
      const response = await getNodeExecStatus(data.instanceId);
      this.wokflowSpinning = false;
      const nodes = response.data.nodes;
      this.nodekeyMap = nodes.reduce((acc, { nodeKey, nodeName }) => {
        acc[nodeKey] = nodeName;
        return acc;
      }, {});
      const nodeStatusMap = nodes.reduce((acc, { nodeKey, nodeStatus }) => {
        acc[nodeKey] = nodeStatus;
        return acc;
      }, {});
      const uiInfo = response.data.model.uiInfo;
      this.styleData = {
        // width: '500px',
        height: "592px",
        scale: 0.5,
      };
      this.$nextTick(() => {
        this.$refs.fow.fowupdata(JSON.parse(uiInfo), nodeStatusMap);
      });
    },
    initializationData() {
      this.temeactiveKey = "1";
      this.activeKey = "1";
      this.selectagent = null;
      this.teamSelectagent = null;
    },
    async teamorpersonal() {
      // 切换团队-个人
      // this.personalSearch = ''
      // this.teamSearch = ''
      console.log("刷新了");
      this.UrlParamsRunTaskId = undefined;
      this.UrlParamsInstanceId = undefined;
      this.UrlParamsType = undefined;
      this.agencyTasksShow = false;
      if (this.agentmenu === "1") {
        await this.personalinitList();
      } else if (this.agentmenu === "2") {
        await this.teaminitList();
      } else if (this.agentmenu === "3") {
        this.$nextTick(() => {
          this.$refs.agencyTasks.teamorpersonal();
        });
        this.participate = false;
        this.agencyTasksShow = true;
      } else if (this.agentmenu === "4") {
        this.participate = true;
        this.agencyTasksShow = true;
      }
    },
    // 个人代办查询
    async personalinitList() {
      this.data = [];
      this.spinning = true;
      this.initializationData();
      // queryParam.name
      try {
        const result = await queryMyTask({
          pageNo: 1,
          pageSize: 1000,
          search: this.queryParam.name,
          searchType: "1",
          serviceWorkOrderNumber: "",
          // 'serviceWorkOrderNumber': this.queryParam.name,
          serviceWorkOrderNumberList: [],
          tenantId: 0,
          userId: "",
          runExecutionId:
            this.UrlParamsRunTaskId && this.UrlParamsType === "user"
              ? this.UrlParamsRunTaskId
              : undefined,
        });
        this.data = result.data.rows;
        this.onSearch();
        if (this.data.length > 0) {
          console.log("==================");
          this.selectagent = this.data[0];
          await this.examineClick(this.selectagent);
        }
      } catch (e) {
        console.error("请求失败,但走这就对了", e);
        this.spinning = false;
      }
      this.spinning = false;
    },
    // 团队代办查询
    async teaminitList() {
      this.teamData = [];
      this.spinning = true;
      this.initializationData();
      // teamqueryParam.name
      try {
        const result = await queryTeamTask({
          pageNo: 1,
          pageSize: 1000,
          search: this.teamqueryParam.name,
          searchType: "1",
          serviceWorkOrderNumber: "",
          // 'serviceWorkOrderNumber': this.teamqueryParam.name,
          serviceWorkOrderNumberList: [],
          tenantId: 0,
          userId: "",
          runExecutionId:
            this.UrlParamsRunTaskId && this.UrlParamsType === "time"
              ? this.UrlParamsRunTaskId
              : undefined,
        });
        this.teamData = result.data.rows;
        this.teamonSearch();
        if (this.teamData.length > 0) {
          this.teamSelectagent = this.teamData[0];
          await this.getTeamTaskDetail(this.teamSelectagent);
        }
      } catch (e) {
        console.error("请求失败,但走这就对了", e);
        this.spinning = false;
      }
      this.spinning = false;
    },
    // 展示代办项
    async initList() {
      await this.teaminitList();
      await this.personalinitList();
    },
    async submitForm(buttonitem) {
      let okRes;
      if (buttonitem.value === "驳回") {
        okRes = await this.$refs[this.approVal.ref].formModelOk(false);
      } else {
        okRes = await this.$refs[this.approVal.ref].formModelOk();
      }
      const { form, actualValue } = okRes;
      if (buttonitem.value === "驳回" && !form?.approvalComments) {
        this.$message.error("驳回意见必填");
        return;
      }
      const { instanceId, taskId, formId } = this.examineObj;
      // eslint-disable-next-line no-unused-expressions
      const readUnlimitedMap = this.dataSourceUiMapDTOList
        ?.map((item) => {
          if (item.readUnlimited) {
            return {
              columnKey: item.dataColumnKey,
              instanceId: instanceId,
              taskId: taskId,
              value: actualValue[item.dataColumnKey],
              viewId: formId,
            };
          }
        })
        .filter(Boolean);

      console.log(readUnlimitedMap, "readUnlimitedMap");
      if (readUnlimitedMap) {
        await saveUnlimitedValue(readUnlimitedMap);
      }

      const data = {
        instanceId: "",
        modelId: this.examineObj.modelId,
        processType: "DEFAULT",
        runVariableMap: form,
        userId: "",
        viewId: this.examineObj.formId,
        version: this.examineObj.version,
        serverInfoMap: {
          sponsor: {},
          tenantId: "1000",
        },
      };

      const res = await apiProcessCheck(data);
      if (res.code !== 200) {
        throw new Error("验证失败");
      }

      const result = await apiComplete({
        param: { ...form, approvalResult: buttonitem.value },
        executionId: this.examineObj.runExecutionId,
        runTaskId: this.examineObj.runTaskId,
        instanceId: this.examineObj.instanceId,
        viewId: this.examineObj.formId,
      });
      if (result.code === 200) {
        this.$message.success("操作成功");
        this.initList();
      }
      this.showComponent = false;
      this.visible = false;
      this.$forceUpdate();
    },
    async buttonClick(buttonitem) {
      try {
        await this.$nextTick();
        if (["同意", "提交"].includes(buttonitem.value)) {
          await this.$refs[this.approVal.ref].$refs.infoViews.validate(
            async (valid) => {
              // 校验
              if (valid) {
                await this.submitForm(buttonitem);
              }
            }
          );
        } else {
          await this.submitForm(buttonitem);
        }
      } catch (e) {
        console.log(e);
      }
    },
    async handleOk(buttonitem) {
      const self = this;
      if (buttonitem.key === "结束") {
        // this.$confirm({
        //   title: "确定结束？",
        //   content: (h) => <div>确定结束？</div>,
        //   async onOk() {
        //     await self.buttonClick(buttonitem);
        //   },
        //   onCancel() {},
        //   class: "test",
        // });
      } else {
        await this.buttonClick(buttonitem);
      }
    },
    formUiMap(fromList) {
      // 执行map
      for (const key in fromList) {
        fromList[key] = fromList[key][fromList[key].length - 1];
        fromList[key].formUi = repairUiData(
          fromList[key].formUi,
          fromList[key].viewDataMappingDTOList
        );
        if (fromList[key].appType === "process" && fromList[key].subProcess) {
          // eslint-disable-next-line no-undef
          fromList[key].subProcess = this.formUiMap(
            fromList[key].subProcess.processCompletedNodeResDTOMap
          );
        }
      }
      return Object.values(fromList);
    },
    async callbackTab(val) {
      // 切换审批跟流程视图
      if (val === "1") {
        // 审批
        this.$refs[this.approVal.ref].setEditorKey(); // 解决切换tab,富文本返显问题
      } else if (val === "2") {
        // 流转记录
        // await this.()
        // await this.scrollToBottom()
      } else if (val === "3") {
        // 流程图
        this.flowchart(this.selectagent);
      }
    },
    async teamCallbackTab(val) {
      // 切换审批跟流程视图
      if (val === "1") {
        // 审批
      } else if (val === "2") {
        // 流转记录
      } else if (val === "3") {
        // 流程图
        this.flowchart(this.teamSelectagent);
      }
    },
    // 遍历获取所有子节点
    getChildArr(data) {
      data.forEach((res) => {
        if (res.children && res.children.length > 0) {
          this.getChildArr(res.children);
        } else {
          this.childArr.push(res._id);
        }
      });
      return this.childArr;
    },
    transferDate(Time) {
      return Time ? moment(parseInt(Time)).format("YYYY-MM-DD HH:mm:ss") : "";
    },
  },
  watch: {
    teamSearch: {
      immediate: true, // 初始化时执行一次
      handler() {
        this.teamonSearch();
      },
    },
    personalSearch: {
      immediate: true, // 初始化时执行一次
      handler() {
        this.onSearch();
      },
    },
    queryParam: {
      // 节流防抖抖抖～～
      handler() {
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.personalinitList();
        }, 1000);
      },
      deep: true,
    },
    teamqueryParam: {
      // 节流防抖抖抖～～
      handler() {
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.teaminitList();
        }, 1000);
      },
      deep: true,
    },
  },
};
</script>

<style lang="less" scoped>
:deep(.ant-tabs-nav .ant-tabs-tab) {
  margin: 0px 16px 0px 0px; /* 设置自定义 margin */
}

::v-deep .ant-pro-global-header {
  height: 44px !important;
}

:deep(.custom-input .ant-input) {
  border-radius: 9999px;
  background: var(--color-fill-2);
}

:deep(.custom-input .ant-input:focus) {
  background-color: var(--color-bg-2);
}

:deep(.ant-checkbox-checked .ant-checkbox-inner) {
  background-color: var(--color-primary-6);
  border-color: var(--color-primary-6);
}

:deep(.ant-divider-horizontal) {
  margin: 0px;
}
:deep(.ant-timeline-item) {
  padding: 0 0 10px;
}
:deep(.ant-timeline-item-content) {
  top: -10px;
}
:deep(.ant-tabs-tab) {
  font-size: 18px;
}
:deep(.ant-tabs-bar) {
  margin: 0px;
}
:deep(.ant-tag) {
  border-radius: 4px;
}

:deep(.ant-tabs-nav .ant-tabs-tab) {
  padding: 12px 0px;
  color: var(--color-text-1);
  font-size: 18px;
  font-weight: 500;
}

/* 修改选中标签的颜色 */
:deep(.ant-tabs-nav .ant-tabs-tab.ant-tabs-tab-active) {
  color: var(--color-primary-6);
  padding: 12px 0px;
}

/* 强化工作台左侧列表选中态的可见性（避免被其他样式覆盖） */
:deep(.agentcontent .card.active) {
  border: 2px solid var(--color-primary-6) !important;
  box-shadow: 0 0 0 1px var(--color-primary-6);
}
</style>

<style lang="less">
@import "./home.less";
</style>
